package com.mlethe.library.multi.pay.listener;

import com.mlethe.library.multi.pay.MultiMedia;
import com.tencent.mobileqq.openpay.api.IOpenApiListener;
import com.tencent.mobileqq.openpay.data.base.BaseResponse;
import com.tencent.mobileqq.openpay.data.pay.PayResponse;

import org.json.JSONObject;

/**
 * QQ支付回调监听
 *
 * @Author Mlethe
 * @Date 2023/3/15
 */
public class OpenApiListener implements IOpenApiListener {

    private OnPayListener mOnPayListener;

    public OpenApiListener(OnPayListener listener) {
        this.mOnPayListener = listener;
    }

    @Override
    public void onOpenResponse(BaseResponse response) {
        try {
            if (response instanceof PayResponse) {
                PayResponse payResponse = (PayResponse) response;
                int code = payResponse.retCode;
                if (payResponse.isSuccess()) {
                    // 支付成功
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("apiName", payResponse.apiName);
                        jsonObject.put("serialNumber", payResponse.serialNumber);
                        jsonObject.put("retMsg", payResponse.retMsg);
                        jsonObject.put("transactionId", payResponse.transactionId);
                        jsonObject.put("payTime", payResponse.payTime);
                        jsonObject.put("callbackUrl", payResponse.callbackUrl);
                        jsonObject.put("totalFee", payResponse.totalFee);
                        jsonObject.put("spData", payResponse.spData);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mOnPayListener != null) {
                        mOnPayListener.onComplete(MultiMedia.QQ_PAY, jsonObject);
                    }
                } else if (code == -1) {
                    // 用户取消
                    if (mOnPayListener != null) {
                        mOnPayListener.onCancel(MultiMedia.QQ_PAY);
                    }
                } else if (code == -2) {
                    // 登录态超时
                    if (mOnPayListener != null) {
                        mOnPayListener.onFailure(MultiMedia.QQ_PAY, code);
                    }
                } else if (code == -3) {
                    // 重复提交订单
                    if (mOnPayListener != null) {
                        mOnPayListener.onFailure(MultiMedia.QQ_PAY, code);
                    }
                } else {
                    if (mOnPayListener != null) {
                        mOnPayListener.onFailure(MultiMedia.QQ_PAY, code);
                    }
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            if (mOnPayListener != null) {
                mOnPayListener.onDestroy();
            }
            mOnPayListener = null;
        }
    }
}
